package cn.com.kh;

import java.io.IOException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.DeflateDecompressingEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class DownHtmlToFile {
	private static final Log log = LogFactory.getLog(DownHtmlToFile.class);

	public static void main(String[] args) {

		get("https://www.cnblogs.com/barrysgy/p/13027296.html", "d:" + File.separator + "test.html");

	}

	public static boolean get(String urlString, String filePath) {
		boolean reCode = false;
		try {
			reCode = getUrlContent(urlString, filePath);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return reCode;
	}

	private static boolean getUrlContent(String urlString, String filePath) throws IOException, ClientProtocolException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(urlString);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse httpGetResponse = httpClient.execute(httpGet);

		if (httpGetResponse.getStatusLine().getStatusCode() == 200) {
			HttpEntity httpEntity = httpGetResponse.getEntity();
			if (httpEntity.getContentEncoding() != null) {
				if ("gzip".equalsIgnoreCase(httpEntity.getContentEncoding().getValue())) {
					httpEntity = new GzipDecompressingEntity(httpEntity);
				} else if ("deflate".equalsIgnoreCase(httpEntity.getContentEncoding().getValue())) {
					httpEntity = new DeflateDecompressingEntity(httpEntity);
				}
			}
			// 取出应答字符串
			boolean result = enCodetoString(httpEntity, filePath);

			return result;
		}
		return false;
	}

	public static boolean enCodetoString(final HttpEntity entity, String filePath) throws IOException, ParseException {

		boolean reCode = false;
		if (entity == null) {
			throw new IllegalArgumentException("HTTP entity may not be null");
		}
		InputStream instream = entity.getContent();
		if (instream == null) {
			return reCode;
		}

		try {

			String resultHtml = "";
			InputStreamReader reader = new InputStreamReader(instream, "UTF-8");
			BufferedReader iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				resultHtml += line;
			}

			if (resultHtml != null && resultHtml.length() > 0) {
				reCode = writeFile(resultHtml, filePath);
			}

		} finally {
			instream.close();
		}
		return reCode;
	}

	public static boolean writeFile(String message, String FilePath) {

		long tstartTime, tendTime, startTime, endTime;

		tstartTime = System.currentTimeMillis();
		log.debug("-File写入本地文件参数 Start time:" + tstartTime + "-emlFilePath:" + FilePath);

		// 将文件内容写入本地服务器
		int i = 0;
		File dirAll = new File(FilePath);
		FileWriter fw = null;
		do {
			startTime = System.currentTimeMillis();

			log.debug("-File[" + i + "]开始将文件内容写入本地服务器:" + "-emlFilePath:" + FilePath);
			try {
				// 文件夹路径是否存在不存在则创建
				File dir = new File(dirAll.getParent());
				if (!dir.exists()) {
					log.debug("-File[" + i + "]创建EML所需路径:" + dirAll.getParent());
					dir.mkdirs();
				}

				// 检查目标文件是否存在，不存在则创建
				if (!dirAll.exists()) {
					log.debug("-File[" + i + "]创建写入文件:" + dirAll.getName());
					dirAll.createNewFile();
				}
				// 向目标文件中写入内容
				fw = new FileWriter(FilePath, false);
				fw.write(message);
				fw.flush();

				fw.close();

				log.debug("-File[" + i + "]写入文件完成...");

			} catch (Exception e) {
				log.error("-File[" + i + "]写入文件失败：", e);
				e.printStackTrace();
			} finally {
				try {
					if (fw != null) {
						fw.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				endTime = System.currentTimeMillis();

				log.debug("-File[" + i + "]写入文件结束 Start time:" + startTime + "; End time:" + endTime + "; Run Time:" + (endTime - startTime) + "(ms)");

				i++;

			}
		} while (!dirAll.exists() && i < 3);

		tendTime = System.currentTimeMillis();
		log.debug("-File写入本地文件结束 End time:" + tendTime + "; Run Time:" + (tendTime - tstartTime) + "(ms)");

		return dirAll.exists();

	}

}
